package com.itheima.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.mapper.StudentMapper;
import com.itheima.pojo.entity.PageResult;
import com.itheima.pojo.entity.Student;
import com.itheima.pojo.query.StudentQueryParam;
import com.itheima.service.StudentService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * @author zzw
 * @date 2025/4/27
 * @description 学员服务实现接口
 */
@Slf4j
@Service
public class StudentServiceImpl implements StudentService {

    @Autowired
    private StudentMapper studentMapper;

    /**
     * 分页查询学员信息
     *
     * @param studentQueryParam 查询参数
     * @return PageResult<Student> 分页结果
     */
    @Override
    public PageResult<Student> page(StudentQueryParam studentQueryParam) {
        // 1.开启分页参数
        PageHelper.startPage(studentQueryParam.getPage(), studentQueryParam.getPageSize());

        // 2.获取分页结果
        Page<Student> studentList = studentMapper.page(studentQueryParam);

        // 3.返回分页结果
        return new PageResult<>(studentList.getTotal(), studentList.getResult());
    }

    /**
     * 删除学员信息
     *
     * @param ids 学员id数组
     */
    @Override
    public void deleteByIds(Integer[] ids) {
        studentMapper.deleteByIds(ids);
    }

    /**
     * 新增学员信息
     *
     * @param student 学员信息
     */
    @Override
    public void insert(Student student) {
        student.setCreateTime(LocalDateTime.now());
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.insert(student);
    }

    /**
     * 根据id查询学员信息
     *
     * @param id 学员id
     * @return Student 学员信息
     */
    @Override
    public Student getById(Integer id) {
        return studentMapper.getById(id);
    }

    /**
     * 更新学员信息
     *
     * @param student 学员信息
     */
    @Override
    public void update(Student student) {
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);
    }

    /**
     * 处理学员违规信息
     *
     * @param id    学员id
     * @param score 违规分数
     */
    @Override
    public void handleViolation(Integer id, Short score) {
        // 1.根据id获取学员信息
        Student student = studentMapper.getById(id);

        // 2.更新学员违规信息
        // 2.1 更新学员违规次数
        student.setViolationCount((short) (student.getViolationCount() + 1));
        // 2.2 添加学员违规分数
        student.setViolationScore((short) (student.getViolationScore() + score));

        // 3.更新数据库
        student.setUpdateTime(LocalDateTime.now());
        studentMapper.update(student);
    }
}
